package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.config.Config;
import com.tf.integrated.entity.*;
import com.tf.integrated.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * OpenAPI管理接口
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "OpenAPI管理接口",description="OpenAPIController")
@RestController
public class OpenAPIController extends BaseController {

    @Autowired
    private ClientInfoService<ClientInfoEntity> clientService;

    @Autowired
    private EventresultvehicleinfoService<EventresultvehicleinfoEntity> vehicleService;

    @Autowired
    private EventresultpersonService<EventresultpersonEntity> personService;

    @Autowired
    private EventresulttricyclesinfoService<EventresulttricyclesinfoEntity> tricycleService;

    @Autowired
    private EventresultpedestriansinfoService<EventresultpedestriansinfoEntity> pedestrianService;

    @Autowired
    private EventresultbikesinfoService<EventresultbikesinfoEntity> bikeService;

    @ApiOperation("查询预警布控-车辆属性")
    @GetMapping("/openapi/warning/vehicleAttr")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public JSONObject vehicleSearch(@RequestParam Map<String, String> data) {
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0) {
            String client = data.get("client");
            String deviceId = data.get("deviceid");
            String token = data.get("token");
            String startTime = data.get("starttime");
            String endTime = data.get("endtime");
            String offset = data.get("offset");
            String count = data.get("count");
            if (isExist(client) && isExist(deviceId) && isExist(token) && isExist(startTime) && isExist(endTime) && isExist(offset) && isExist(count)) {
                EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
                ew0.eq("clientname", client);
                ew0.eq("token", token);
                List<ClientInfoEntity> clientList = clientService.selectList(ew0);
                if (clientList != null && clientList.size() > 0) {
                    JSONArray devices = JSONArray.parseArray(clientList.get(0).getRelationdevice());
                    if (devices != null && devices.size() > 0) {
                        List<String> devicesList = devices.toJavaList(String.class);
                        if (devicesList.contains(deviceId)) {
                            String preUrl = Config.getStarturlpre(deviceId);
                            String xToken = Config.getmCurtoken(deviceId);
                            if (isExist(preUrl) && isExist(xToken)) {
                                String query = Config.buildMap(data);
                                HttpHeaders headers = new HttpHeaders();
                                headers.set("X-Token", xToken);
                                String analyseResults = Config.client(preUrl + "/warning/vehicleAttr/?" + query, HttpMethod.GET, null, headers);
                                JSONObject result = JSONObject.parseObject(analyseResults);
                                JSONObject jsonData = result.getJSONObject("Data");
                                if(jsonData!=null){
                                    JSONArray array = jsonData.getJSONArray("VehStrWarning");
                                    jsonData.put("VehStrWarning",array.toJSONString());
                                }
                                return result;
                            } else {
                                returnData.put("Code",1006);
                                returnData.put("Message", "设备处于离线状态");
                            }
                        } else {
                            returnData.put("Code",1005);
                            returnData.put("Message", "该设备ID不是该用户关联的设备");
                        }
                    } else {
                        returnData.put("Code",1004);
                        returnData.put("Message", "该客户没有关联的设备");
                    }
                } else {
                    returnData.put("Code",1003);
                    returnData.put("Message", "client或token错误");
                }
            } else {
                returnData.put("Code",1002);
                returnData.put("Message", "参数错误");
            }
        }else{
            returnData.put("Code",1001);
            returnData.put("Message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("新增预警布控-车辆属性")
    @PostMapping("/openapi/warning/vehicleAttr")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public JSONObject vehicleAdd(@RequestParam Map<String, String> data) {
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0) {
            String client = data.get("client");
            String deviceId = data.get("deviceid");
            String token = data.get("token");
            String name = data.get("name");
            String reason = data.get("reason");
            if (isExist(client) && isExist(deviceId) && isExist(token) && isExist(name) && isExist(reason)) {
                EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
                ew0.eq("clientname", client);
                ew0.eq("token", token);
                List<ClientInfoEntity> clientList = clientService.selectList(ew0);
                if (clientList != null && clientList.size() > 0) {
                    JSONArray devices = JSONArray.parseArray(clientList.get(0).getRelationdevice());
                    if (devices != null && devices.size() > 0) {
                        List<String> devicesList = devices.toJavaList(String.class);
                        if (devicesList.contains(deviceId)) {
                            String preUrl = Config.getStarturlpre(deviceId);
                            String xToken = Config.getmCurtoken(deviceId);
                            if (isExist(preUrl) && isExist(xToken)) {
                                String query = Config.buildMap(data);
                                HttpHeaders headers = new HttpHeaders();
                                headers.set("X-Token", xToken);
                                String analyseResults = Config.client(preUrl + "/warning/vehicleAttr/?" + query, HttpMethod.POST, null, headers);
                                return JSONObject.parseObject(analyseResults);
                            } else {
                                returnData.put("Code",1006);
                                returnData.put("Message", "设备处于离线状态");
                            }
                        } else {
                            returnData.put("Code",1005);
                            returnData.put("Message", "该设备ID不是该用户关联的设备");
                        }
                    } else {
                        returnData.put("Code",1004);
                        returnData.put("Message", "该客户没有关联的设备");
                    }
                } else {
                    returnData.put("Code",1003);
                    returnData.put("Message", "client或token错误");
                }
            } else {
                returnData.put("Code",1002);
                returnData.put("Message", "参数错误");
            }
        }else{
            returnData.put("Code",1001);
            returnData.put("Message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("获取结构化数据列表接口")
    @GetMapping("/openapi/structure")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public JSONObject structureDataList(@RequestParam Map<String, String> data) {
        JSONObject returnData = new JSONObject();
        returnData.put("Data", null);
        if (data != null && data.size() > 0) {
            String client = data.get("client");
            String deviceId = data.get("deviceid");
            String token = data.get("token");
            String startTime = data.get("starttime");
            String endTime = data.get("endtime");
            if (isExist(client) && isExist(deviceId) && isExist(token) && isExist(startTime) && isExist(endTime)) {
                EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
                ew0.eq("clientname", client);
                ew0.eq("token", token);
                List<ClientInfoEntity> clientList = clientService.selectList(ew0);
                if (clientList != null && clientList.size() > 0) {
                    JSONArray devices = JSONArray.parseArray(clientList.get(0).getRelationdevice());
                    if (devices != null && devices.size() > 0) {
                        List<String> devicesList = devices.toJavaList(String.class);
                        if (devicesList.contains(deviceId)) {
                            String chn = data.get("chn");
                            List<JSONObject> all = new ArrayList<>();
                            Integer[] types = getTypes(data.get("type"));
                            for (int type : types) {
                                switch (type) {
                                    case 1: {
                                        all.addAll(getListTypeOne(deviceId, chn,startTime,endTime));
                                        break;
                                    }
                                    case 2: {
                                        all.addAll(getListTypeTwo(deviceId, chn,startTime,endTime));
                                        break;
                                    }
                                    case 3: {
                                        all.addAll(getListTypeThree(deviceId, chn,startTime,endTime));
                                        break;
                                    }
                                    case 4: {
                                        all.addAll(getListTypeFour(deviceId, chn,startTime,endTime));
                                        break;
                                    }
                                    case 5: {
                                        all.addAll(getListTypeFive(deviceId, chn,startTime,endTime));
                                        break;
                                    }
                                }
                            }
                            int total = all.size();
                            all.sort((a1, a2) -> a2.getDate("CreateTime").compareTo(a1.getDate("CreateTime")));
                            all = all.subList(0, Math.min(200, all.size()));
                            returnData.put("Data", all);
                            returnData.put("Code", 200);
                            returnData.put("Total",total);
                            returnData.put("Message", "操作成功");
                        } else {
                            returnData.put("Code",1005);
                            returnData.put("Message", "该设备ID不是该用户关联的设备");
                        }
                    } else {
                        returnData.put("Code",1004);
                        returnData.put("Message", "该客户没有关联的设备");
                    }
                } else {
                    returnData.put("Code",1003);
                    returnData.put("Message", "client或token错误");
                }
            } else {
                returnData.put("Code",1002);
                returnData.put("Message", "参数错误");
            }
        }else{
            returnData.put("Code",1001);
            returnData.put("Message", "参数不存在");
        }
        return returnData;
    }

    public ArrayList<JSONObject> getListTypeOne(String host,String chn,String starttime,String endtime){
        EntityWrapperHandle<EventresultvehicleinfoEntity> ew = new EntityWrapperHandle<EventresultvehicleinfoEntity>();
        ew.eq("deviceid",host);
        String[] chnIds=getStringArray(chn);
        if(chnIds.length>0){
            String sql = getSqlAndEqualOr("chn",chnIds);
            ew.and(sql);
        }
        ew.between("createtime",starttime,endtime);
        List<EventresultvehicleinfoEntity> list = vehicleService.selectList(ew);
        ArrayList<JSONObject> array=new ArrayList<>();
        if(list!=null&&list.size()>0){
            for (EventresultvehicleinfoEntity eventresultvehicleinfoEntity : list) {
                JSONObject json = new JSONObject();
                json.put("CarType", eventresultvehicleinfoEntity.getCartype());
                json.put("Chn", eventresultvehicleinfoEntity.getChn());
                json.put("CoDriver", eventresultvehicleinfoEntity.getCodriver());
                json.put("CoNoBelt", eventresultvehicleinfoEntity.getConobelt());
                json.put("Color", eventresultvehicleinfoEntity.getColor());
                json.put("DriveWay", eventresultvehicleinfoEntity.getDriveway());
                json.put("Drop", eventresultvehicleinfoEntity.getDrop());
                json.put("FullPicPath", eventresultvehicleinfoEntity.getFullpicpath());
                json.put("HasCall", eventresultvehicleinfoEntity.getHascall());
                json.put("HasCrash", eventresultvehicleinfoEntity.getHascrash());
                json.put("HasRack", eventresultvehicleinfoEntity.getHasrack());
                json.put("HasSpareTire", eventresultvehicleinfoEntity.getHassparetire());
                json.put("HasSunroof", eventresultvehicleinfoEntity.getHassunroof());
                json.put("IsDanger", eventresultvehicleinfoEntity.getIsdanger());
                json.put("IsSlag", eventresultvehicleinfoEntity.getIsslag());
                json.put("MainNoBelt", eventresultvehicleinfoEntity.getMainnobelt());
                json.put("MarkerNum", eventresultvehicleinfoEntity.getMarkernum());
                json.put("ObjPicPath", eventresultvehicleinfoEntity.getObjpicpath());
                json.put("Orientation", eventresultvehicleinfoEntity.getOrientation());
                json.put("Paper", eventresultvehicleinfoEntity.getPaper());
                json.put("PlateInfo", eventresultvehicleinfoEntity.getPlateinfo());
                json.put("Rect", eventresultvehicleinfoEntity.getRect());
                json.put("StyleName", eventresultvehicleinfoEntity.getStylename());
                json.put("Time", eventresultvehicleinfoEntity.getTime());
                json.put("Type", eventresultvehicleinfoEntity.getType());
                json.put("ResultType", 1);
                json.put("CreateTime", eventresultvehicleinfoEntity.getCreatetime());
                array.add(json);
            }
        }
        return array;
    }

    public ArrayList<JSONObject> getListTypeTwo(String host,String chn,String starttime,String endtime){
        EntityWrapperHandle<EventresulttricyclesinfoEntity> ew = new EntityWrapperHandle<EventresulttricyclesinfoEntity>();
        ew.eq("deviceid",host);
        String[] chnIds=getStringArray(chn);
        if(chnIds.length>0){
            String sql = getSqlAndEqualOr("chn",chnIds);
            ew.and(sql);
        }
        ew.between("createtime",starttime,endtime);
        List<EventresulttricyclesinfoEntity> list = tricycleService.selectList(ew);
        ArrayList<JSONObject> array=new ArrayList<>();
        if(list!=null&&list.size()>0) {
            for (EventresulttricyclesinfoEntity eventresulttricyclesinfoEntity : list) {
                JSONObject json = new JSONObject();
                json.put("Chn", eventresulttricyclesinfoEntity.getChn());
                json.put("Convertible", eventresulttricyclesinfoEntity.getConvertible());
                json.put("DriveWay", eventresulttricyclesinfoEntity.getDriveway());
                json.put("FullPicPath", eventresulttricyclesinfoEntity.getFullpicpath());
                json.put("Manned", eventresulttricyclesinfoEntity.getManned());
                json.put("ObjPicPath", eventresulttricyclesinfoEntity.getObjpicpath());
                json.put("Rect", eventresulttricyclesinfoEntity.getRect());
                json.put("RoofColor", eventresulttricyclesinfoEntity.getRoofcolor());
                json.put("Time", eventresulttricyclesinfoEntity.getTime());
                json.put("Type", eventresulttricyclesinfoEntity.getType());
                json.put("ResultType", 2);
                json.put("CreateTime", eventresulttricyclesinfoEntity.getCreatetime());
                array.add(json);
            }
        }
        return array;
    }

    public ArrayList<JSONObject> getListTypeThree(String host,String chn,String starttime,String endtime){
        EntityWrapperHandle<EventresultpedestriansinfoEntity> ew = new EntityWrapperHandle<EventresultpedestriansinfoEntity>();
        ew.eq("deviceid",host);
        String[] chnIds=getStringArray(chn);
        if(chnIds.length>0){
            String sql = getSqlAndEqualOr("chn",chnIds);
            ew.and(sql);
        }
        ew.between("createtime",starttime,endtime);
        List<EventresultpedestriansinfoEntity> list = pedestrianService.selectList(ew);
        ArrayList<JSONObject> array=new ArrayList<>();
        if(list!=null&&list.size()>0) {
            for (EventresultpedestriansinfoEntity eventresultpedestriansinfoEntity : list) {
                JSONObject json = new JSONObject();
                json.put("Age", eventresultpedestriansinfoEntity.getAge());
                json.put("Baby", eventresultpedestriansinfoEntity.getBaby());
                json.put("Bag", eventresultpedestriansinfoEntity.getBag());
                json.put("BottomColor", eventresultpedestriansinfoEntity.getBottomcolor());
                json.put("BottomType", eventresultpedestriansinfoEntity.getBottomtype());
                json.put("Chn", eventresultpedestriansinfoEntity.getChn());
                json.put("DriveWay", eventresultpedestriansinfoEntity.getDriveway());
                json.put("FullPicPath", eventresultpedestriansinfoEntity.getFullpicpath());
                json.put("Glasses", eventresultpedestriansinfoEntity.getGlasses());
                json.put("Hair", eventresultpedestriansinfoEntity.getHair());
                json.put("Hat", eventresultpedestriansinfoEntity.getHat());
                json.put("Knapsack", eventresultpedestriansinfoEntity.getKnapsack());
                json.put("Mask", eventresultpedestriansinfoEntity.getMask());
                json.put("MessengerBag", eventresultpedestriansinfoEntity.getMessengerbag());
                json.put("ObjPicPath", eventresultpedestriansinfoEntity.getObjpicpath());
                json.put("Orientation", eventresultpedestriansinfoEntity.getOrientation());
                json.put("Rect", eventresultpedestriansinfoEntity.getRect());
                json.put("Sex", eventresultpedestriansinfoEntity.getSex());
                json.put("ShoulderBag", eventresultpedestriansinfoEntity.getShoulderaag());
                json.put("Time", eventresultpedestriansinfoEntity.getTime());
                json.put("Type", eventresultpedestriansinfoEntity.getType());
                json.put("Umbrella", eventresultpedestriansinfoEntity.getUmbrella());
                json.put("UpperColor", eventresultpedestriansinfoEntity.getUppercolor());
                json.put("UpperTexture", eventresultpedestriansinfoEntity.getUppertexture());
                json.put("UpperType", eventresultpedestriansinfoEntity.getUppertype());
                json.put("ResultType", 3);
                json.put("CreateTime", eventresultpedestriansinfoEntity.getCreatetime());
                array.add(json);
            }
        }
        return array;
    }

    public ArrayList<JSONObject> getListTypeFour(String host,String chn,String starttime,String endtime){
        EntityWrapperHandle<EventresultbikesinfoEntity> ew = new EntityWrapperHandle<EventresultbikesinfoEntity>();
        ew.eq("deviceid",host);
        String[] chnIds=getStringArray(chn);
        if(chnIds.length>0){
            String sql = getSqlAndEqualOr("chn",chnIds);
            ew.and(sql);
        }
        ew.between("createtime",starttime,endtime);
        List<EventresultbikesinfoEntity> list = bikeService.selectList(ew);
        ArrayList<JSONObject> array=new ArrayList<>();
        if(list!=null&&list.size()>0) {
            for (EventresultbikesinfoEntity eventresultbikesinfoEntity : list) {
                JSONObject json = new JSONObject();
                json.put("Age", eventresultbikesinfoEntity.getAge());
                json.put("Baby", eventresultbikesinfoEntity.getBaby());
                json.put("Bag", eventresultbikesinfoEntity.getBag());
                json.put("BottomColor", eventresultbikesinfoEntity.getBottomcolor());
                json.put("BottomType", eventresultbikesinfoEntity.getBottomtype());
                json.put("Chn", eventresultbikesinfoEntity.getChn());
                json.put("DriveWay", eventresultbikesinfoEntity.getDriveway());
                json.put("FullPicPath", eventresultbikesinfoEntity.getFullpicpath());
                json.put("Glasses", eventresultbikesinfoEntity.getGlasses());
                json.put("Hair", eventresultbikesinfoEntity.getHair());
                json.put("Hat", eventresultbikesinfoEntity.getHat());
                json.put("Knapsack", eventresultbikesinfoEntity.getKnapsack());
                json.put("Mask", eventresultbikesinfoEntity.getMask());
                json.put("MessengerBag", eventresultbikesinfoEntity.getMessengerbag());
                json.put("ObjPicPath", eventresultbikesinfoEntity.getObjpicpath());
                json.put("Orientation", eventresultbikesinfoEntity.getOrientation());
                json.put("Rect", eventresultbikesinfoEntity.getRect());
                json.put("Sex", eventresultbikesinfoEntity.getSex());
                json.put("ShoulderBag", eventresultbikesinfoEntity.getShoulderaag());
                json.put("Time", eventresultbikesinfoEntity.getTime());
                json.put("Type", eventresultbikesinfoEntity.getType());
                json.put("Umbrella", eventresultbikesinfoEntity.getUmbrella());
                json.put("UpperColor", eventresultbikesinfoEntity.getUppercolor());
                json.put("UpperTexture", eventresultbikesinfoEntity.getUppertexture());
                json.put("UpperType", eventresultbikesinfoEntity.getUppertype());
                json.put("ResultType", 4);
                json.put("CreateTime", eventresultbikesinfoEntity.getCreatetime());
                array.add(json);
            }
        }
        return array;
    }

    public ArrayList<JSONObject> getListTypeFive(String host,String chn,String starttime,String endtime){
        EntityWrapperHandle<EventresultpersonEntity> ew = new EntityWrapperHandle<EventresultpersonEntity>();
        ew.eq("deviceid",host);
        String[] chnIds=getStringArray(chn);
        if(chnIds.length>0){
            String sql = getSqlAndEqualOr("chn",chnIds);
            ew.and(sql);
        }
        ew.between("createtime",starttime,endtime);
        List<EventresultpersonEntity> list = personService.selectList(ew);
        ArrayList<JSONObject> array=new ArrayList<>();
        if(list!=null&&list.size()>0) {
            for (EventresultpersonEntity eventresultpersonEntity : list) {
                JSONObject json = new JSONObject();
                json.put("Age", eventresultpersonEntity.getAge());
                json.put("Chn", eventresultpersonEntity.getChn());
                json.put("FullPicPath", eventresultpersonEntity.getFullpicpath());
                json.put("Glasses", eventresultpersonEntity.getGlasses());
                json.put("Hair", eventresultpersonEntity.getHair());
                json.put("Hat", eventresultpersonEntity.getHat());
                json.put("Mask", eventresultpersonEntity.getMask());
                json.put("ObjPicPath", eventresultpersonEntity.getObjpicpath());
                json.put("Rect", eventresultpersonEntity.getRect());
                json.put("RegionName", eventresultpersonEntity.getRegionname());
                json.put("Sex", eventresultpersonEntity.getSex());
                json.put("Time", eventresultpersonEntity.getTime());
                json.put("Type", eventresultpersonEntity.getType());
                json.put("ResultType", 5);
                json.put("CreateTime", eventresultpersonEntity.getCreatetime());
                array.add(json);
            }
        }
        return array;
    }

    public boolean isExist(String value){
        return value != null && !value.equals("");
    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public Integer[] getTypes(String types){
        if(!isExist(types)){
            return new Integer[]{1,2,3,4,5};
        }
        String[] str = types.split(",");
        List<Integer> list = new ArrayList<>();
        for (String value : str) {
            if (isInteger(value)) {
                list.add(Integer.parseInt(value));
            }
        }
        return list.toArray(new Integer[0]);
    }

    public String[] getStringArray(String s){
        if(isExist(s)){
            return s.split(",");
        }
        return new String[0];
    }

    public String getSqlAndEqualOr(String field,String[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append(field).append("='").append(values[i]).append("'");
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }
}